//
//  MoyaHandySet.swift
//  NewXueBa
//
//  Created by Shine on 2019/5/30.
//  Copyright © 2019 jmxQAQ. All rights reserved.
//

import Foundation

extension ObservableType where E == Response {
    public func mapModel<T: HandyJSON>(_ type: T.Type) throws -> Observable<T> {
        return flatMap { response -> Observable<T> in
            return Observable.just(response.mapModelObser(T.self))
        }
    }
}

extension Response {
    
    func mapModelObser<T: HandyJSON>(_ type: T.Type) -> T {
        let jsonString = String(data: data, encoding: .utf8)
        print(jsonString ?? "请求打印----mapModelObser")
        guard let mode = JSONDeserializer<T>.deserializeFrom(json: jsonString) else {
            fatalError() }
        return mode
    }
    
    func mapModel<T: HandyJSON>(_ type: T.Type) throws -> T {
        let jsonString = String(data: data, encoding: .utf8)
        print(jsonString ?? "请求打印----mapModel")
        guard let mode = JSONDeserializer<T>.deserializeFrom(json: jsonString) else { throw MoyaError.jsonMapping(self) }
        return mode
    }
    
}

extension MoyaProvider {
    
    @discardableResult
    open func request<T: HandyJSON>(_ target: Target,
                                    model: T.Type,
                                    completion: ((_ returnData: T?) -> Void)?) -> Cancellable? {
        print("请求地址\(target.baseURL)\(target.path)")
        return request(target, completion: { (result) in
            guard let completion = completion else { return }
            guard let returnTData = try? result.value?.mapModel(model) else {
                completion(nil)
                return
            }
            // 利用基础model 检测网络请求
            if let observeData = try? result.value?.mapModel(BaseModel.self) {
                if observeData.code == 4 {
                    print("token过期")
                    UIApplication.shared.delegate?.window??.rootViewController = UIStoryboard.viewController(from: .LoginSB, viewControllerClass: StudyLoginVC.self)
                } else if observeData.code != 0 {
                    print("无法连接服务器")
                    BCBaseVC.showTipMsgInWindow("无法连接服务器", time: 1)
                }
            }
            
            print(returnTData)
            completion(returnTData)
        })
    }
}
